package com.started;

import java.util.concurrent.TimeUnit;

public class ThreadTest {
    public static void main(String[] args) {
        T4 sale = new T4();
        Thread thread1 = new Thread(sale);
        Thread thread2 = new Thread(sale);
        Thread thread3 = new Thread(sale);

        thread1.start();
        thread2.start();
        thread3.start();
    }
}

class T4 implements Runnable {
    //所有的售票窗口共享 100 张票
    private static int tickets = 10;

    @Override
    public void run() {
        while (true) {
            int i = sale();
            if (i == 1) {
                break;
            }
        }
    }

    // 在方法上加锁
    public synchronized int sale() {
        if (tickets <= 0) {
            System.out.println(Thread.currentThread().getName() + "售空");
            return 1;
        }
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // Thread.currentThread().getName() 表示当前线程的名字
        System.out.println(Thread.currentThread().getName()
                + "卖了一张票，剩余票数：" + (--tickets));
        return 0;
    }
}



